import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class EventChannelDemo extends StatefulWidget {
  @override
  _EventChannelDemoState createState() => _EventChannelDemoState();
}

class _EventChannelDemoState extends State<EventChannelDemo> {
  // 创建 EventChannel 实例
  static const EventChannel _eventChannel =
      EventChannel('samples.flutter.io/charging');

  String _chargingStatus = '未知';
  StreamSubscription? _streamSubscription;

  @override
  void initState() {
    super.initState();
    // 监听来自原生的事件流
    _startListening();
  }

  // 开始监听充电状态事件
  void _startListening() {
    _streamSubscription = _eventChannel.receiveBroadcastStream().listen(
      (event) {
        setState(() {
          _chargingStatus = event.toString();
        });
      },
      onError: (error) {
        setState(() {
          _chargingStatus = '监听出错: $error';
        });
      },
    );
  }

  // 停止监听
  void _stopListening() {
    _streamSubscription?.cancel();
    setState(() {
      _chargingStatus = '已停止监听';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('EventChannel 示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Icon(
                      Icons.battery_charging_full,
                      size: 64,
                      color: Colors.green,
                    ),
                    SizedBox(height: 16),
                    Text(
                      '充电状态监听',
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 16),
                    Text(
                      '当前状态: $_chargingStatus',
                      style: TextStyle(fontSize: 16),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 32),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _startListening,
                  child: Text('开始监听'),
                ),
                ElevatedButton(
                  onPressed: _stopListening,
                  child: Text('停止监听'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }
}
